import os, pygame
from pygame.locals import *

#functions to create our resources
def load_image(name):
    try:
        image = pygame.image.load(name)
    except pygame.error, message:
        print 'Cannot load image:', name
        raise SystemExit, message
    image = image.convert_alpha()
    return image, image.get_rect()
    
#functions to create our resources
def load_frame(name):
    try:
        image = pygame.image.load(name)
    except pygame.error, message:
        print 'Cannot load image:', name
        raise SystemExit, message
    image = image.convert_alpha()
    return image

def bluranddim(image, blur=3, darken=0.5):
    # Grab a copy image
    bg = image.convert_alpha()
    bgs = image.convert_alpha()
    # Blur it
    bg = pygame.transform.smoothscale(bg, (bg.get_width()/blur, bg.get_height()/blur))
    bg = pygame.transform.smoothscale(bg, (bgs.get_width(), bgs.get_height()))
    # Darken it
    bgs.fill((0,0,0,(255*darken)))
    bg.blit(bgs, (0,0))
    return bg

def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer or not pygame.mixer.get_init():
        return NoneSound()
    fullname = os.path.join('data','sfx', name)
    try:
        sound = pygame.mixer.Sound(fullname)
    except pygame.error, message:
        print 'Cannot load sound:', fullname
        raise SystemExit, message
    return sound
    
def rewriteconf(properties,file):
    cfgfile = open(os.path.join('data', file, ".txt"))
    str = cfgfile.read()
    str = str.split('\n')
    cfgfile.close()
    
    for replacement in properties:
        for line in str:
            line = line.split('=')
            if line[0] == replacement[0]:
                line[1] = replacement[1]
                properties.remove(replacement)
            line = line.join('=')
            
    # At this point, all the properties that are in the file have been rewritten.
    # All the properties that have been rewritten have been removed from the list.
    for replacement in properties:
        str.append(replacement[0] + "=" + replacement[1])

    file = open(os.path.join('data', file, ".txt"), 'w')
    file.write(str.join('\n'))
    file.close()